package com.slashmanx.goals2u.others;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.slashmanx.goals2u.GoalsDatabaseManager;
import com.slashmanx.goals2u.Match;

import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class Utilities {
	
	public static void showDialog(Context ctx, String title, String msg) {
		
		AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(ctx);
        dlgAlert.setMessage(msg);
        dlgAlert.setTitle(title);
        dlgAlert.setPositiveButton("OK", null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
	}
	
	public static boolean isOnline(Context ctx) 
	{
	    ConnectivityManager connectivityManager  = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;

	}

	
	public static ArrayList<Match> getScores(GoalsDatabaseManager db, String type, String league) throws JSONException
	{
		ArrayList<Match> MatchList = null;
		JSONObject 	jObject 		= Utilities.getJSONfromURL("http://www.slashmanx.com/android/goals.php");
		if(jObject != null)
		{
			JSONObject 	matchesObject 	= jObject.getJSONObject("matches");
			JSONArray 	matchArray 		= matchesObject.getJSONArray("match");
		
		
			for(int i = 0; i < matchArray.length(); i++)
			{
				Match temp = new Match();
				temp.setHomeTeam(matchArray.getJSONObject(i).getString("home_team").toString());
				temp.setAwayTeam(matchArray.getJSONObject(i).getString("away_team").toString());
				temp.setMinute(Integer.parseInt(matchArray.getJSONObject(i).getString("minute").toString()));
				temp.setHomeScore(Integer.parseInt(matchArray.getJSONObject(i).getString("home_score").toString()));
				temp.setAwayScore(Integer.parseInt(matchArray.getJSONObject(i).getString("away_score").toString()));
				temp.setType(matchArray.getJSONObject(i).getString("type").toString());
				temp.setLeague(matchArray.getJSONObject(i).getString("league").toString());
				
				db.addMatch(temp);
				
			}
			MatchList = db.getAllMatches(type, league);
		}
		
		
		return MatchList;
	}
	
	public static JSONObject getJSONfromURL(String url) {

		//initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		}catch(Exception e){
			// Connection error
			Log.e("CONNECTION!!!!", "Connection Error\n"+ e.getMessage() );
			return null;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			// reading error
			Log.e("READING!!!!", "Reading Error");
		}

		//try parse the string to a JSON object
		try{
	        	jArray = new JSONObject(result);
		}catch(JSONException e){
			//JSON Parsing Error
			Log.e("PARSING!!!!", "Parsing Error");
		}

		return jArray;
	}
	

}
